/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    Text,
    Button,
    useTheme,
    useToast,
    LayerLoading,
    Spinner,
    Input,
    TwoHalfRightPanel,
    Container,
    MenuItem,
    MenuList,
    InputLine,
    Select,
    CheckSwitch,
    IconButton,
    IconArrowLeft,
    IconKey, VerticalMenu, DdMenuItem, CommitInput
} from "customize-easy-ui-component";
//import {   useAddToTask } from "../db";
//import { useSession } from "../auth";

//import { Link as RouterLink,  } from "wouter";
import useBuildRequestMutation from "./hook/useBuildRequestMutation";
import NewDevice from "../device/NewDevice";

import {Link as RouterLink} from "../routing/Link";
import {useContext} from "react";
import UserContext from "../routing/UserContext";
import {ContainerDesignClsTil, getFeeTitleFe} from "../dict/feeTitleFe";

import {ChooseUnit} from "../unit/ChooseUnit";
import {getFormatDate} from "../common/tool";
import {ChooseDevice} from "../device/ChooseDevice";
import { 业务类型s, } from "../device/edit/CommnBase";
import RoutingContext from "../routing/RoutingContext";
import {ChooseEqps} from "../comp/ChooseEqps";
//import {Spinner} from "../comp/Spinner";
//import { awaitExpression } from "@babel/types";

//[HOOK限制]按钮点击函数内部直接上toast()或toaster.notify()很可能无法正常显示。而放在函数组件顶层render代码前却能正常。

/**申请单的 类型字典表： 后端前端适配的关键代码指引。【modtype, desc, cannew】
 * 非常关键！！ 两端的代码耦合点。前端操作不如后端方便安全,目前只考虑后端执行业务操作。 cannew=0表示不能直接new()需要从关联对象菜单提出申请。
 * */
export const 申请单类型s=[["eqpOpenclose","设备状态变更",1],["deviceUnits","设备的单位变更",1],["technicalField","关键技术参数变更",1],
    ["revisionPermit","申请报告书修订",1],["revisionExecution","报告书修订执行",1],["stopInspec","暂停监检申请",0],["taskDelay","任务延期申请",0],
   ["cancelTask","取消任务申请",0]];

export const RequestTypeMap = new Map();
申请单类型s.map(([enumt,desc], i) => (RequestTypeMap.set(enumt, desc)) );


export interface ComposeProps {
}
//这种路由写法：params:{ id }是空的，不会接收上级<Route />路由器给的:id。
/*申请单新增： 有些类型申请单不用在这里创建。
考虑合理性交互模式：ChooseEqps组件新增加更多设备的显示？若都放在TwoHalf左边也不友好，最好直接放在主页面也就是TwoHalf右半边页面上返回就能弹出显示。
* */
export const AddToRequest = ({
    ...other
}: ComposeProps) => {
    const theme = useTheme();
    const toast = useToast();
    const {user} = useContext(UserContext);
    const {save, field}= window.history.state?.state??{};      //通用伪对话框传递格式field=上次跳转目标选择字段。

    //if(save && field)   save[field]= {id, name: unit.name};
    //从跳转伪对话框页面之前做了保存的编辑器恢复数据。
    // const [servu, setServu] = React.useState(save? save.servu : null);
    // const [ptno, setPtno] = React.useState(save? save.ptno : null);
    const [mod, setMod] = React.useState(save? save.mod : 'technicalField');
    let  delayds=31;      //默认任务日期 Default task date延后天数=31天 Delayed days
    const [date, setDate] = React.useState(save&&save.date? save.date : getFormatDate(new Date(delayds*1000*60*60*24 + Date.now()) ));
    console.log("AddTask返回last页面 save=", save,"date=",date);

    const {call:buildTaskFunc,doing,result, called, reset}= useBuildRequestMutation();
    console.log("AddToTask页面刷新result:", result ,"called=",called);
   //const servu=window.history.state?.state?.servu;      //外部注入的参数
    console.log("AddtoTassk其它path传递参数来=",window.history.state?.state);
    const defaultIspu= localStorage['默认检验机构']? JSON.parse(localStorage['默认检验机构']) : undefined;
    const [ispu, setIspu] = React.useState(save? save.ispu : defaultIspu);
    /**编辑器正在编辑数据的暂时保留(路由切换切回后还能取回)，从为对话框页面路由返回之后再利用已经修改数据。
     * 多个设备一起挑选 麻烦，这里【限制】保留一个设备meqp的跳转恢复。
     * */
    async function confirmation() {
        return {
             mod, ispu
        };
    }
    const { history } = useContext(RoutingContext);


  //if(doing)  return <Spinner/>;
  return (
        <TwoHalfRightPanel
            back={
                <RouterLink  href="/tasks">
                    <IconButton label="后退"  variant="ghost"
                        size="md"  noBind  icon={<IconArrowLeft />}
                        css={{
                            marginRight: theme.spaces.sm,
                            [theme.mediaQueries.md]: {
                                display: "none"
                            }
                        }}
                    />
                </RouterLink>
             }
            menu={
                <VerticalMenu>
                    <DdMenuItem label="其他功能"
                                onClick={ () => {
                                }}/>
                </VerticalMenu>
            }
            title={ `新的协议受理申请单` }
        >
            <Text variant="h5">新申请单准备发起，发起应答有id后继续编制申请单明细表单的模式</Text>
              {!called ? (
              <div>
                <Text  variant="h6">申请单类型决定后续表单，选定初始化之后不能变更</Text>
{/*                  <InputLine label={`服务单位:`}>
                      <ChooseUnit id={servu?.id} name={servu?.name} field={'servu'}
                                  autoFocus={field==='servu'}
                                  onCancel={() => { setServu(undefined) }}
                                  onDialog={async () => { return await confirmation() } }
                      />
                  </InputLine>
                  <InputLine label={`协议编号(标识):`}>
                      <CommitInput  value={ ptno || ''}  onSave={txt=> setPtno(txt||undefined)}/>
                  </InputLine>*/}
                  <InputLine label={`申请单类型:`}>
                      <Select inputSize="md"  value={ mod || ''}
                              onChange={e => setMod( e.currentTarget.value||undefined ) } >
                          { 申请单类型s.map(([enumv,title, cannew], i) => (
                              (cannew===1) &&
                                <option key={i} value={enumv}>{title}</option>
                          )) }
                      </Select>
                  </InputLine>
                  <InputLine label={`检验检测机构:`}>
                      <Select  css={{ minWidth:'230px' }}
                              defaultValue={ispu}
                              onChange={e =>{
                                  setIspu( e.currentTarget.value || '');
                                  localStorage['默认检验机构'] =JSON.stringify(e.currentTarget.value || '');
                              } } >
                          <option key={0} value={''}></option>
                          { user?.ispUnits.map((agency: any, i: number) => (<option key={i+1} value={agency.unit.id}>{agency.unit.name}</option> )) }
                      </Select>
                  </InputLine>
              </div>
              )
              :
              (
                  <div>
                    <Text variant="h6">生成的新协议ID： {(result as any)?.id}</Text>
                      <Button size={'lg'} intent="primary"
                              onPress={() => {
                                  history.push(`/request/${result.id}`);
                              }}
                      >进入该协议的细节编制
                      </Button>
                </div>
              )
              }

          {!called &&
              <Button size={'lg'}
                              intent="primary"
                              disabled={doing || !ispu}
                              css={{ marginLeft: theme.spaces.sm }}
                              onPress={() => {
                                  //devs: meqp&&[ meqp.id ]
                                  buildTaskFunc('','ADD',
                                      { mod, ispu}
                                  );
                              }}
              >
              新通用申请单准备发起
              </Button>
          }
          <Spinner doing={doing}/>
        </TwoHalfRightPanel>
  );
};

export default AddToRequest;
